package homework2.server;

import homework2.common.Message;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Server监听端口服务类
 *
 * @author jian
 * @date 2024/01/08 16:49
 **/
public class Server {
    private ServerSocket serverSocket;

    /**
     * 监听端口
     *
     * @param port
     */

    public Server(int port) {

        try {

            this.serverSocket = new ServerSocket(port);

            System.out.println("服务端启动成功，端口：" + port);

        } catch (IOException e) {

            System.out.println("服务端启动失败");

        }

    }


    public void start() {
        Socket socket = null;//如果没有客户端连接，就会阻塞在这里
        try {
            while (true) { //当和某个客户端连接后，会继续监听, 因此while
                socket = serverSocket.accept();
                //得到socket关联的输入流
                InputStream inputStream = socket.getInputStream();
                ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
                Message message = (Message) objectInputStream.readObject();
                String id = message.getUserId();
                System.out.println("用户" + id + "登录");
                ServerConnectClientThread serverConnectClientThread = new ServerConnectClientThread(socket, id);
//                //启动该线程
                serverConnectClientThread.start();
//                //把该线程对象，放入到一个集合中，进行管理.
                ManageClientThreads.addClientThread(id, serverConnectClientThread);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {

            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}
